package summary;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/8 10:14
 * https://leetcode-cn.com/problems/spiral-matrix/
 */
public class Title54 {

    /**                     up
     *                left     right
     * @param matrix      down
     * @return
     */
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        int row = matrix.length;
        int column = matrix[0].length;
        int n = row * column;
        int up = 0, down = row - 1;
        int left = 0, right = column - 1;
        int count = 0;
        while (count < n) {
            //左到右
            for (int j = left; j <= right && count < n; j++) {
                result.add(matrix[up][j]);
                count++;
            }
            up++;
            //上到下
            for (int i = up; i <= down && count < n; i++) {
                result.add(matrix[i][right]);
                count++;
            }
            right--;
            //从右到左
            for (int j = right; j >= left && count < n; j--) {
                result.add(matrix[down][j]);
                count++;
            }
            down--;
            //从下到上
            for (int i = down; i >= up && count < n; i--) {
                result.add(matrix[i][left]);
                count++;
            }
            left++;
        }
        return result;
    }


    public List<Integer> spiralOrder1(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;
        int sum = n * m;
        int count = 0;
        int left = 0, right = m - 1;
        int up = 0, down = n - 1;
        List<Integer> result = new ArrayList<>();
        while (count < sum) {
            //左->右
            for (int i = left; i <= right && count < sum; i++) {
                result.add(matrix[up][i]);
                count++;
            }
            up++;
            //上->下
            for (int i = up; i <= down&& count < sum; i++) {
                result.add(matrix[i][right]);
                count++;
            }
            right--;
            //右->左
            for (int i = right; i >= left && count < sum; i--) {
                result.add(matrix[down][i]);
                count++;
            }
            down--;
            //下->上
            for (int i = down; i >= up && count < sum; i--) {
                result.add(matrix[i][left]);
                count++;
            }
            left++;
        }
        return result;
    }

    public static void main(String[] args) {

    }
}
